<?php

namespace api\modules\v1\forms\patient;

use common\models\patient\ClinicImg;
use Yii;
use yii\base\Model;
use common\models\member\Member;
use common\models\patient\User;
use common\models\base\BodyParts;

/**
 * 治疗图片
 *
 * Class ClinicImgForm
 * @package api\modules\v1\forms\patient
 */
class ClinicImgForm extends Model
{
    /**
     * 图片IDs【多个用','分割】
     *
     * @var
     */
    public $ids;

    /**
     * 项目ID
     *
     * @var
     */
    public $project_id;

    /**
     * 患者诊疗号
     *
     * @var
     */
    public $patient_card_id;

    /**
     * 治疗图片【json格式：[{id: '图片ID', body_parts_id: '部位ID'}] 】
     *
     * @var
     */
    public $clinic_imgs;


    /**
     * 患者信息
     *
     * @var
     */
    protected $patientInfo;

    /**
     * 部位列表
     *
     * @var
     */
    protected $bodyPartsList;

    /**
     * 患者列表
     *
     * @var
     */
    protected $clinicImgList;


    /**
     * 部位数组
     *
     * @var
     */
    protected $clinicImgArr;


    public function rules()
    {
        return [
            // 参数验证
            [['project_id', 'patient_card_id', 'clinic_imgs'], 'required', 'message' => '{attribute}不能为空', 'on' => ['edit']],
            [['ids', 'project_id'], 'required', 'message' => '{attribute}不能为空', 'on' => ['delete']],

            [['project_id'], 'checkProjectId', 'skipOnEmpty' => false, 'on' => ['edit', 'delete']],
            [['patient_card_id'], 'checkPatientCardId', 'skipOnEmpty' => false, 'on' => ['edit']],
            [['clinic_imgs'], 'checkClinicImgs', 'skipOnEmpty' => false, 'on' => ['edit']],
            [['ids'], 'checkIds', 'skipOnEmpty' => false, 'on' => ['delete']],
        ];
    }

    public function scenarios()
    {
        $scenarios = parent::scenarios();

        // 编辑
        $scenarios['edit'] = ['project_id', 'patient_card_id', 'clinic_imgs'];

        // 删除
        $scenarios['delete'] = ['ids', 'project_id'];

        return $scenarios;
    }

    /**
     * @return array
     */
    public function attributeLabels()
    {
        return [
            'ids' => '图片IDs',
            'project_id' => '项目ID',
            'patient_card_id' => '患者诊疗号',
            'clinic_imgs' => '治疗图片',
        ];
    }

    /**
     * 检验项目ID
     *
     * @param $attribute
     * @return bool
     */
    public function checkProjectId($attribute)
    {
        // 自用接口直接删除
        if (isset(Yii::$app->params['test-delete-img']) && Yii::$app->params['test-delete-img'] == true) {
            return true;
        }


        if (Yii::$app->user->identity->member->is_super == Member::IS_SUPER_YES) {
            return true;
        }

        $attr = Yii::$app->services->attr->findInfo([
            'member_id' => Yii::$app->user->identity->member_id,
            'project_id' => $this->project_id,
        ]);

        if (!$attr) {
            $this->addError($attribute, '未绑定当前项目，无法操作');
            return true;
        }
    }

    /**
     * 检验患者诊疗号
     *
     * @param $attribute
     * @return bool
     */
    public function checkPatientCardId($attribute)
    {
        if ($this->hasErrors()) {
            return true;
        }

        $patient = $this->getPatient();
        if (!$patient) {
            $this->addError($attribute, '参数错误[id_error]');
            return true;
        }

        if ($patient->status == User::STATUS_DELETE) {
            $this->addError($attribute, '患者已删除，无法操作');
            return true;
        }
    }

    /**
     * 校验治疗图片
     *
     * @param $attribute
     */
    public function checkClinicImgs($attribute)
    {
        if ($this->hasErrors()) {
            return true;
        }

        // 治疗图片
        $clinicImgsArr = $this->getClinicImgList();

        // 治疗图片列表
        $clinicImgsIds = array_column($clinicImgsArr, 'id');
        $clinicImgList = Yii::$app->services->patientClinicImg->findList([
            'id' => $clinicImgsIds,
            'project_id' => $this->project_id,
            'patient_card_id' => $this->patient_card_id,
            'indexBy' => 'id',
        ]);

        // 部位列表
        $bodyPartsIds = array_column($clinicImgsArr, 'body_parts_id');
        $this->bodyPartsList = $bodyPartsList = Yii::$app->services->bodyParts->findList([
            'id' => $bodyPartsIds,
            'status' => [BodyParts::STATUS_ENABLE, BodyParts::STATUS_INVALID],
            'indexBy' => 'id',
        ]);

        foreach ($clinicImgsArr as $row) {
            if (!isset($row['id']) || !isset($clinicImgList[$row['id']])) {
                $this->addError($attribute, '参数错误[clinic_imgs_id_error]');
                return true;
            }

            if (!isset($row['body_parts_id']) || ($row['body_parts_id'] > 0 && !isset($bodyPartsList[$row['body_parts_id']]))) {
                $this->addError($attribute, '参数错误[clinic_imgs_body_error]');
                return true;
            }
        }
    }

    /**
     * 校验治疗图片IDs
     *
     * @param $attribute
     */
    public function checkIds($attribute)
    {
        if ($this->hasErrors()) {
            return true;
        }

        // 治疗图片列表
        $clinicImgList = $this->getClinicImgByIdList();

        if (empty($clinicImgList)) {
            $this->addError($attribute, '参数错误[ids_error]');
            return true;
        }
    }

    /**
     * 获取患者信息
     *
     * @return User|null
     */
    public function getPatient()
    {
        if (is_null($this->patientInfo)) {
            $this->patientInfo = Yii::$app->services->patientUser->findInfo([
                'patient_card_id' => $this->patient_card_id,
            ]);
        }

        return $this->patientInfo;
    }

    /**
     * 获取编辑图片列表
     *
     * @return mixed
     */
    public function getClinicImgList()
    {
        if (is_null($this->clinicImgArr)) {
            $clinicImg = json_decode($this->clinic_imgs, true);
            $clinicImgArr = [];
            foreach ($clinicImg as $row) {
                if (empty($row['body_parts_id'])) {
                    continue;
                }

                $clinicImgArr[] = $row;
            }
            $this->clinicImgArr = $clinicImgArr;
        }

        return $this->clinicImgArr;
    }

    /**
     * 获取部位列表
     *
     * @return mixed
     */
    public function getBodyPartsList()
    {
        return $this->bodyPartsList;
    }

    /**
     * 根据IDs获取治疗图片列表
     *
     * @return array|\yii\db\ActiveRecord[]
     */
    public function getClinicImgByIdList()
    {
        if (is_null($this->clinicImgList)) {
            $ids = explode(',', $this->ids);
            $this->clinicImgList = Yii::$app->services->patientClinicImg->findList([
                'id' => $ids,
                'status' => ClinicImg::STATUS_ENABLE
            ]);
        }

        return $this->clinicImgList;
    }
}
